var express = require("express");
var router = express.Router();
var path = require("path");
// 获取验证模块
var authorization = require(path.join(process.cwd(), "/modules/authorization"));

// 购物车管理模块
var ShopCartSer = authorization.getService("ShopCart");
// 获取购物车列表
router.get(
  "/:user_id",
  // 参数验证
  function (req, res, next) {
    next();
  },
  // 处理业务逻辑
  function (req, res, next) {
    ShopCartSer.getAllShopCart(req.params.id,function (err, result) {
      if (err) return res.sendResult(null, 400, err);
      res.sendResult(result, 200, "获取成功");
    })(req, res, next);
  }
);

// 新增购物车数据
router.post(
  "/",
  // 参数验证
  function (req, res, next) {
    next();
  },
  // 处理业务逻辑
  // 业务逻辑
  function (req, res, next) {
    ShopCartSer.addShopCart(
      {
        goods_id: req.body.goods_id,
        goods_name: req.body.goods_name,
        goods_price: req.body.goods_price,
        goods_big_logo: req.body.goods_big_logo,
        user_id: req.body.user_id,
        count: 1,
      },
      function (err, attr) {
        if (err) return res.sendResult(null, 400, err);
        res.sendResult(attr, 201, "创建成功");
      }
    )(req, res, next);
  }
);

// 根据购物车id修改
router.post(
  "/:id",
  // 参数验证
  function (req, res, next) {
    next();
  },
  // 处理业务逻辑
  // 业务逻辑
  function (req, res, next) {
    ShopCartSer.updateShopCart(
      req.params.id,
      {
        count: req.body.count,
      },
      function (err, attr) {
        if (err) return res.sendResult(null, 400, err);
        res.sendResult(attr, 201, "更新成功");
      }
    )(req, res, next);
  }
);


// 根据购物车id 删除
router.delete(
    "/:id",
    // 参数验证
    function (req, res, next) {
      next();
    },
    // 处理业务逻辑
    // 业务逻辑
    function (req, res, next) {
        ShopCartSer.deleteShopCart(
        req.params.id,
        function (err, attr) {
          if (err) return res.sendResult(null, 400, err);
          res.sendResult(attr, 200, "删除成功");
        }
      )(req, res, next);
    }
  );

module.exports = router;
